﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
    ViewData["Title"] = "用户管理";
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>用户管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link href="~/libs/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
    <script src="~/libs/scripts/layui-v2.5.6/layui/layui.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div class="layui-card">
        <div class="layui-card-header">
            <div class="layui-row">
                <div class="layui-col-md6">
                    <h2>用户管理</h2>
                </div>
                <div class="layui-col-md6" style="text-align: right;">
                    <button class="layui-btn" id="btnAdd">
                        <i class="layui-icon">&#xe654;</i> 新增用户
                    </button>
                </div>
            </div>
        </div>
        <div class="layui-card-body">
            <!-- 搜索栏 -->
            <form class="layui-form layui-form-pane" lay-filter="searchForm">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">用户名</label>
                        <div class="layui-input-inline">
                            <input type="text" name="userName" placeholder="请输入用户名" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">昵称</label>
                        <div class="layui-input-inline">
                            <input type="text" name="userNickName" placeholder="请输入昵称" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button class="layui-btn" lay-submit lay-filter="searchBtn">
                            <i class="layui-icon">&#xe615;</i> 搜索
                        </button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </form>
            <!-- 数据表格 -->
            <table id="userTable" lay-filter="userTable"></table>
        </div>
    </div>
    <!-- 表格操作列模板 -->
    <script type="text/html" id="tableBar">
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
        <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="assignRole">分配角色</a>
    </script>
    <!-- 新增/编辑用户表单 -->
    <script type="text/html" id="userForm">
        <form class="layui-form" style="padding: 20px;" lay-filter="userForm">
            <input type="hidden" name="id">
            <div class="layui-form-item">
                <label class="layui-form-label">用户名</label>
                <div class="layui-input-block">
                    <input type="text" name="userName" required lay-verify="required" placeholder="请输入用户名" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">密码</label>
                <div class="layui-input-block">
                    <input type="password" name="userPwd" required lay-verify="required" placeholder="请输入密码" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">昵称</label>
                <div class="layui-input-block">
                    <input type="text" name="userNickName" required lay-verify="required" placeholder="请输入昵称" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="submitForm">立即提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </script>
    <!-- 角色分配弹窗模板 -->
    <script type="text/html" id="roleAssignForm">
        <form class="layui-form" style="padding: 20px;" lay-filter="roleAssignForm">
            <input type="hidden" name="userId">
            <div class="layui-form-item">
                <label class="layui-form-label">角色列表</label>
                <div class="layui-input-block" id="roleCheckbox">
                    <!-- 角色复选框将通过JavaScript动态加载 -->
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="submitRoleAssign">保存</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </script>
    <script>
        layui.use(['table', 'form', 'layer'], function () {
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;
            var $ = layui.$;
            
            // 存储表格状态
            var tableConfig = {
                page: { curr: 1 },
                sort: {}
            };

            // 初始化表格
            table.render({
                elem: '#userTable',
                url: '/RBAC/ShowUser',
                page: true,
                where: {}, // 初始无条件
                request: {
                    pageName: 'PageIndex', // 页码的参数名称，默认：page
                    limitName: 'PageCount'  // 每页数据量的参数名，默认：limit
                },
                cols: [[
                    {field: 'id', title: 'ID', width: 80, sort: true},
                    {field: 'userName', title: '用户名', width: 120},
                    {field: 'userNickName', title: '昵称', width: 120},
                    {title: '操作', toolbar: '#tableBar', width: 220, fixed: 'right'}
                ]]
            });
            
            // 监听排序事件
            table.on('sort(userTable)', function(obj){
                // 保存排序状态
                tableConfig.sort = {
                    field: obj.field,
                    type: obj.type
                };
                
                // 重载表格
                table.reload('userTable', {
                    initSort: obj,
                    where: {
                        field: obj.field,
                        order: obj.type
                    }
                });
            });

            // 搜索按钮点击事件
            form.on('submit(searchBtn)', function(data){
                // 搜索时保持排序状态
                var reloadConfig = {
                    where: data.field,
                    page: { curr: 1 } // 搜索时回到第一页
                };
                
                // 如果有排序状态，保持排序
                if(tableConfig.sort.field){
                    reloadConfig.initSort = tableConfig.sort;
                    reloadConfig.where.field = tableConfig.sort.field;
                    reloadConfig.where.order = tableConfig.sort.type;
                }
                
                table.reload('userTable', reloadConfig);
                return false;
            });

            // 新增按钮点击事件
            $('#btnAdd').on('click', function(){
                layer.open({
                    type: 1,
                    title: '新增用户',
                    area: ['500px', '400px'],
                    content: $('#userForm').html(),
                     success: function(){
                            layui.form.val('userForm', {
                            id: null,
                            userName: '',
                            userPwd: '',
                            userNickName: '',
                            });
                        }
                });
                form.render();
            });

            // 表格工具条事件
            table.on('tool(userTable)', function(obj){
                var data = obj.data;
                if(obj.event === 'del'){
                    layer.confirm('确定删除此用户？', function(index){
                        // 执行删除
                        $.ajax({
                            url: '/RBAC/DeleteUser',
                            type: 'DELETE',
                            data: { userId: data.id },
                            success: function(res){
                                if(res.success){
                                    layer.msg('删除成功');
                                    // 保持当前页面和排序状态的删除
                                    var reloadConfig = {
                                        page: { curr: tableConfig.page.curr }
                                    };
                                    
                                    // 如果有排序状态，保持排序
                                    if(tableConfig.sort.field){
                                        reloadConfig.initSort = tableConfig.sort;
                                    }
                                    
                                    table.reload('userTable', reloadConfig);
                                } else {
                                    layer.msg(res.message);
                                }
                            }
                        });
                        layer.close(index);
                    });
                } else if(obj.event === 'edit'){
                    layer.open({
                        type: 1,
                        title: '编辑用户',
                        area: ['500px', '400px'],
                        content: $('#userForm').html(),
                        success: function(){
                            form.val('userForm', data);
                        }
                    });
                    form.render();
                } else if(obj.event === 'assignRole'){
                    // 打开角色分配弹窗
                    layer.open({
                        type: 1,
                        title: '分配角色',
                        area: ['500px', '400px'],
                        content: $('#roleAssignForm').html(),
                        success: function(layero, index){
                            // 设置用户ID
                            form.val('roleAssignForm', {
                                userId: data.id
                            });
                            
                            // 加载角色列表
                            $.ajax({
                                url: '/RBAC/QueryRole',
                                type: 'GET',
                                success: function(roleRes){
                                    if(roleRes.code === 0 && roleRes.data){
                                        // 获取用户当前角色
                                        $.ajax({
                                            url: '/RBAC/FullUserRole',
                                            type: 'GET',
                                            data: { id: data.id },
                                            success: function(userRoleRes){
                                                if(userRoleRes.code === 0) {
                                                    var roleHtml = '';
                                                    roleRes.data.forEach(function(role){
                                                        var checked = '';
                                                        if (userRoleRes.data && userRoleRes.data.roleId) {
                                                            checked = userRoleRes.data.roleId.includes(role.id) ? 'checked' : '';
                                                        }
                                                        roleHtml += '<input type="checkbox" lay-skin="primary" name="roleIds" value="' + role.id + '" title="' + role.roleName + '" ' + checked + '>';
                                                    });
                                                    $('#roleCheckbox').html(roleHtml);
                                                    form.render('checkbox');
                                                } else {
                                                    layer.msg(userRoleRes.msg || '获取用户角色失败');
                                                }
                                            },
                                            error: function() {
                                                layer.msg('获取用户角色失败');
                                            }
                                        });
                                    }
                                }
                            });
                        }
                    });
                }
            });

            // 表单提交事件
            form.on('submit(submitForm)', function(data){
                var url = data.field.id ? '/RBAC/UpdateUser' : '/RBAC/AddUser';
                var method = data.field.id ? 'PUT' : 'POST';
                var isEdit = data.field.id && data.field.id !== '' && data.field.id !== '0';

                // 确保新增时id为0，避免类型转换错误
                if (data.field.id === '') {
                    data.field.id = 0;
                }

                $.ajax({
                    url: url,
                    type: method,
                    contentType: 'application/json',
                    data: JSON.stringify(data.field),
                    success: function(res){
                        if(res.success){
                            layer.closeAll();
                            layer.msg('保存成功');
                            
                            // 根据操作类型选择重载方式
                            if(isEdit){
                                // 编辑时保持当前页面和排序状态
                                var reloadConfig = {
                                    page: { curr: tableConfig.page.curr }
                                };
                                
                                // 如果有排序状态，保持排序
                                if(tableConfig.sort.field){
                                    reloadConfig.initSort = tableConfig.sort;
                                }
                                
                                table.reload('userTable', reloadConfig);
                            } else {
                                // 新增时正常重载（可能需要跳到第一页显示新数据）
                                table.reload('userTable');
                            }
                        } else {
                            layer.msg(res.message);
                        }
                    }
                });
                return false;
            });

            // 角色分配表单提交
            form.on('submit(submitRoleAssign)', function(data){
                // 获取选中的角色ID
                var roleIds = [];
                $('input[name="roleIds"]:checked').each(function(){
                    roleIds.push(parseInt($(this).val()));
                });

                // 验证是否选择了角色
                if (roleIds.length === 0) {
                    layer.msg('请至少选择一个角色');
                    return false;
                }

                // 构造请求数据
                var postData = {
                    id: 0,                           // EntityDto<int> 要求
                    userId: parseInt(data.field.userId),
                    roleId: roleIds
                };

                // 打印请求数据用于调试
                console.log('提交的数据:', JSON.stringify(postData));

                // 发送请求
                $.ajax({
                    url: '/RBAC/AddUserRole',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(postData),
                    success: function(res){
                        if(res.success){
                            layer.closeAll();
                            layer.msg(res.message || '角色分配成功');
                            table.reload('userTable');
                        } else {
                            layer.msg(res.message || '角色分配失败');
                        }
                    },
                    error: function(xhr, status, error) {
                        var errorMessage = '';
                        try {
                            var response = JSON.parse(xhr.responseText);
                            if(response.errors) {
                                errorMessage = Object.values(response.errors).join('; ');
                            } else {
                                errorMessage = response.message || '请求失败';
                            }
                        } catch(e) {
                            errorMessage = xhr.responseText || '未知错误';
                        }
                        layer.msg(errorMessage);
                    }
                });
                return false;
            });
        });
    </script>
</body>
</html>
